package com.koudai.reader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.AdWallManager;
import com.koudai.reader.conponment.BookChaptersDialog;
import com.koudai.reader.conponment.LoadbookDialog;
import com.koudai.reader.db.SingleDAO;
import com.koudai.reader.util.Constant;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.util.UnZip;
import com.koudai.reader.util.Utils;
import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;
import com.umeng.analytics.MobclickAgent;

public class BookShelfActivity extends BaseActivity implements OnScrollListener, OnCreateContextMenuListener {

    ListView mybookList;
    private ListViewAdapter mListViewAdapter;
    private ImageView refresh;
    private ProgressBar loading;
    private Map<Integer, Book> bookDataList = new HashMap<Integer, Book>();
    Handler internalhandler = new Handler();

    private TextView score;
    private TextView capability;

    private ImageView search;
    private ImageView isVip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.bookshelf_app);

        mListViewAdapter = new ListViewAdapter();

        mybookList = (ListView) findViewById(R.id.book_shelf_list);
        mybookList.setAdapter(mListViewAdapter);

        mybookList.setOnScrollListener(this);

        refresh = (ImageView) findViewById(R.id.refresh);
        search = (ImageView) findViewById(R.id.search_btn);
        loading = (ProgressBar) findViewById(R.id.loading);

        capability = (TextView) findViewById(R.id.capability);

        loadBookDialog = new LoadbookDialog(BookShelfActivity.this.getParent());

        search.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View paramView) {
                Intent intent = new Intent();
                intent.setClass(BookShelfActivity.this, SearchBookActivity.class);
                BookShelfActivity.this.startActivity(intent);
            }
        });

        refresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View paramView) {

                refresh.setVisibility(View.GONE);
                loading.setVisibility(View.VISIBLE);

                if (EndUser.getInstance().isVip()) {

                    new Thread(new Runnable() {

                        @Override
                        public void run() {

                            handlerUpdate();

                            internalhandler.post(new Runnable() {
                                public void run() {
                                    refresh.setVisibility(View.VISIBLE);
                                    loading.setVisibility(View.GONE);
                                }
                            });
                        }

                    }).start();
                } else if (EndUser.getInstance().getGold() + Constant.operation.get("bookupdate") >= 0) {
                    final Dialog dialog = new AlertDialog.Builder(BookShelfActivity.this).setTitle("书海小助手温馨提示")
                            .setMessage("（一键更新）功能需消耗" + Constant.operation.get("bookupdate") + "积分")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    new Thread(new Runnable() {

                                        @Override
                                        public void run() {
                                            if (HttpUtils.goldOperation("bookupdate")) {
                                                EndUser.getInstance().updateGold(Constant.operation.get("bookupdate"));
                                                EndUser.getInstance().setBookCount(EndUser.getInstance().getBookCount() + 3);
                                                handlerUpdate();
                                                internalhandler.post(new Runnable() {
                                                    public void run() {
                                                        capability.setText("容量（" + EndUser.getInstance().getBookCount() + "本）");
                                                    }
                                                });
                                            } else {
                                                internalhandler.post(new Runnable() {
                                                    public void run() {
                                                        Toast.makeText(BookShelfActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                                                    }
                                                });

                                            }
                                            internalhandler.post(new Runnable() {
                                                public void run() {
                                                    score.setText(EndUser.getInstance().getGlodStr());
                                                    refresh.setVisibility(View.VISIBLE);
                                                    loading.setVisibility(View.GONE);
                                                }
                                            });
                                        }
                                    }).start();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    refresh.setVisibility(View.VISIBLE);
                                    loading.setVisibility(View.GONE);
                                }
                            }).create();

                    dialog.show();

                } else if (EndUser.getInstance().getGold() + Constant.operation.get("bookupdate") < 0) {
                    final Dialog dialog = new AlertDialog.Builder(BookShelfActivity.this).setTitle("温馨提示")
                            .setMessage("亲，一键更新属于高级功能(" + Constant.operation.get("bookupdate") + "积分/次)，您的积分不足")
                            .setPositiveButton("获取积分", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    // TODO 积分墙
                                    AdWallManager.openAppOffers(BookShelfActivity.this);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    refresh.setVisibility(View.VISIBLE);
                                    loading.setVisibility(View.GONE);
                                }
                            }).create();

                    dialog.show();
                    refresh.setVisibility(View.VISIBLE);
                    loading.setVisibility(View.GONE);
                }

            }
        });
    }

    private void handlerUpdate() {
        List<Integer> bookids = new ArrayList<Integer>();

        for (Book book : bookDataList.values()) {
            bookids.add(book.getBookid());
        }

        try {
            List<Book> serverlist = HttpUtils.updateBookshelf(bookids);

            List<Book> needUpdateList = new ArrayList<Book>();

            for (Book serverItem : serverlist) {
                for (Book localItem : bookDataList.values()) {
                    if ((serverItem.getBookid() == localItem.getBookid()) && !serverItem.getServerLastChapter().equals(localItem.getServerLastChapter())) {
                        localItem.setServerLastChapter(serverItem.getServerLastChapter());
                        needUpdateList.add(localItem);
                        break;
                    }
                }
            }

            if (needUpdateList.size() == 0) {
                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {

                        Toast.makeText(BookShelfActivity.this, "暂时无更新", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {

                for (final Book updateBook : needUpdateList) {
                    internalhandler.post(new Runnable() {
                        public void run() {
                            Toast.makeText(BookShelfActivity.this, "开始更新" + updateBook.getTitle(), Toast.LENGTH_SHORT).show();

                        }
                    });
                    downloadFile(updateBook.getDownloadPath(), updateBook.getBookid() + ".zip", updateBook);
                }
            }

        } catch (Exception e) {

            internalhandler.post(new Runnable() {
                public void run() {
                    Toast.makeText(BookShelfActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onResume(this);
        score = (TextView) findViewById(R.id.score);
        score.setText(EndUser.getInstance().getGlodStr());
        capability.setText("容量（" + EndUser.getInstance().getBookCount() + "本）");
        isVip = (ImageView) findViewById(R.id.vip);
        if (EndUser.getInstance().isVip()) {
            isVip.setVisibility(View.VISIBLE);
        } else {
            isVip.setVisibility(View.INVISIBLE);
        }
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        List<Book> list = SingleDAO.getinstance().getBookshelfList();
                        ImageView noBook = (ImageView) findViewById(R.id.book_shelf_no_book);

                        if (list.size() > 0) {
                            noBook.setVisibility(View.GONE);
                            Iterator<Book> iterator = list.iterator();

                            mListViewAdapter.count = 0;
                            while (iterator.hasNext()) {
                                Book book = iterator.next();
                                bookDataList.put(mListViewAdapter.count++, book);
                            }

                            mListViewAdapter.notifyDataSetChanged();
                        } else {

                            noBook.setVisibility(View.VISIBLE);
                        }
                    }
                });

            }
        }).start();

    }

    @Override
    public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onScroll(AbsListView paramAbsListView, int paramInt1, int paramInt2, int paramInt3) {
        // TODO Auto-generated method stub

    }

    /*
     * for app list adapter
     */
    class ListViewAdapter extends BaseAdapter {
        int count = 0;
        LayoutInflater inflater;

        public ListViewAdapter() {
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {

            final Book book = bookDataList.get(position);
            convertView = inflater.inflate(R.layout.bookshelf_item, null);

            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView content = (TextView) convertView.findViewById(R.id.content);
            TextView progress = (TextView) convertView.findViewById(R.id.progress);

            RelativeLayout clickArea = (RelativeLayout) convertView.findViewById(R.id.click_area);
            RelativeLayout clickArea2 = (RelativeLayout) convertView.findViewById(R.id.click_area2);
            RelativeLayout clickArea3 = (RelativeLayout) convertView.findViewById(R.id.click_area3);

            clickArea.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View paramView) {
                    selectedPositionId = position;
                    book.setChapterTitleList(Utils.getChapterList(book));

                    Intent intent = new Intent();
                    intent.setClass(BookShelfActivity.this, ReadBookActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("book", (Serializable) book);
                    intent.putExtras(bundle);
                    BookShelfActivity.this.startActivity(intent);

                }
            });

            // ImageView read = (ImageView) convertView.findViewById(R.id.read);

            clickArea2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View paramView) {
                    new BookChaptersDialog(BookShelfActivity.this, book).show();
                }
            });

            final ImageView refresh = (ImageView) convertView.findViewById(R.id.refresh);
            final ProgressBar loading = (ProgressBar) convertView.findViewById(R.id.loading);

            clickArea3.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    refresh.setVisibility(View.GONE);
                    loading.setVisibility(View.VISIBLE);

                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            List<Book> updateList = null;
                            try {
                                updateList = HttpUtils.updateBookshelf(Arrays.asList(new Integer[] { book.getBookid() }));
                            } catch (Exception e) {
                                internalhandler.post(new Runnable() {
                                    public void run() {

                                        Toast.makeText(BookShelfActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                                    }
                                });

                            }

                            if (updateList != null && updateList.size() == 1) {
                                if (updateList.get(0).getServerLastChapter().equals(book.getServerLastChapter())) {
                                    internalhandler.post(new Runnable() {
                                        public void run() {

                                            Toast.makeText(BookShelfActivity.this, "暂时无更新", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else {
                                    internalhandler.post(new Runnable() {
                                        public void run() {
                                            Toast.makeText(BookShelfActivity.this, "检查到更新，准备中", Toast.LENGTH_SHORT).show();

                                        }
                                    });
                                    downloadFile(book.getDownloadPath(), book.getBookid() + ".zip", updateList.get(0));
                                }
                            }

                            internalhandler.post(new Runnable() {
                                public void run() {

                                    refresh.setVisibility(View.VISIBLE);
                                    loading.setVisibility(View.GONE);
                                }
                            });
                        }
                    }).start();
                }
            });

            title.setText(book.getTitle());
            content.setText("当前末章: " + book.getServerLastChapter());
            progress.setText("阅读进度：第" + (book.getCurrentChapter() + 1) + "节");

            return convertView;
        }

    }

    private int selectedPositionId;

    @Override
    public void onCreateContextMenu(ContextMenu menu, View arg1, ContextMenuInfo arg2) {

        menu.setHeaderTitle("操作菜单");
        menu.add(0, 0, 0, "阅读");
        menu.add(0, 1, 0, "目录");

        super.onCreateContextMenu(menu, arg1, arg2);
    }

    public boolean onContextItemSelected(MenuItem item) {
        final Book book = bookDataList.get(selectedPositionId);
        switch (item.getItemId()) {
        case 0:
            // 读书
            Intent intent = new Intent();
            intent.setClass(BookShelfActivity.this, ReadBookActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("book", (Serializable) book);
            intent.putExtras(bundle);
            BookShelfActivity.this.startActivity(intent);
            break;
        case 1:
            // 目录
            new BookChaptersDialog(BookShelfActivity.this, book).show();
            break;
        case 2:
            // 删除
            final Dialog dialog = new AlertDialog.Builder(BookShelfActivity.this).setTitle("温馨提示").setMessage("确定要删除" + book.getTitle() + "吗")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        }
                    }).create();

            dialog.show();
            break;
        }

        return super.onContextItemSelected(item);
    }

    private int downLoadFileSize;
    private int fileSize_b;
    private LoadbookDialog loadBookDialog;

    public void downloadFile(String fileURL, String fileName, Book book) {
        downLoadFileSize = 0;
        fileSize_b = 0;
        StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        double avail_sd_space = (double) stat_fs.getAvailableBlocks() * (double) stat_fs.getBlockSize();
        // double GB_Available = (avail_sd_space / 1073741824);
        double MB_Available = (avail_sd_space / 10485783);
        // System.out.println("Available MB : " + MB_Available);
        Log.d("MB", "" + MB_Available);
        try {
            File root = new File(Constant.DIR);
            if (root.exists() && root.isDirectory()) {

            } else {
                root.mkdir();
            }
            Log.d("CURRENT PATH", root.getPath());
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.connect();
            int fileSize = c.getContentLength() / 1048576;
            Log.d("FILESIZE", "" + fileSize);
            if (MB_Available <= fileSize) {
                c.disconnect();
                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {

                        Toast.makeText(BookShelfActivity.this, "空间不足", Toast.LENGTH_LONG).show();
                    }
                });
                return;
            }

            String zipFilename = root.getPath() + "/" + fileName;
            String unzipFilePath = root.getPath() + "/" + fileName.substring(0, fileName.length() - 4) + "/";
            FileOutputStream f = new FileOutputStream(new File(zipFilename));

            internalhandler.post(new Runnable() {

                @Override
                public void run() {

                    loadBookDialog.show();
                    loadBookDialog.progress.setMax(fileSize_b);
                    loadBookDialog.tips.setText("请求中...");

                }
            });

            InputStream in = c.getInputStream();
            fileSize_b = c.getContentLength();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {

                if (loadBookDialog.cancel) {
                    // TODO
                }

                f.write(buffer, 0, len1);
                downLoadFileSize += len1;
                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {

                        loadBookDialog.progress.setProgress(downLoadFileSize);
                        float result = ((float) downLoadFileSize / fileSize_b) * 100;
                        loadBookDialog.tips.setText("小说加载中 - " + (int) result + "%");

                    }
                });
            }
            f.close();

            internalhandler.post(new Runnable() {

                @Override
                public void run() {

                    loadBookDialog.progress.setProgress(downLoadFileSize);
                    loadBookDialog.tips.setText("加载完成，处理中");
                }
            });
            UnZip.unzip(zipFilename, unzipFilePath);

            SingleDAO.getinstance().updateLastchapter(book);

            internalhandler.post(new Runnable() {

                @Override
                public void run() {

                    loadBookDialog.tips.setText("处理完毕");

                    loadBookDialog.dismiss();

                    internalhandler.post(new Runnable() {

                        @Override
                        public void run() {

                            mListViewAdapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (loadBookDialog.isShowing()) {
                loadBookDialog.dismiss();
            }
            MobclickAgent.onError(BookShelfActivity.this);
        }
    }
}
